#!/bin/bash

set -x

function env_test(){
	if [ ! $VAULT_ADDR ];then
                echo -e "\033[31mThe value of VAULT_ADDR must be set\033[0m" && exit 1
        fi
	if [ ! $ROLE_ID ];then
		echo -e "\033[31mThe value of ROLE_ID must be set\033[0m" && exit 1
	fi
	if [ ! $SECRET_ID ];then
                echo -e "\033[31mThe value of SECRET_ID must be set\033[0m" && exit 1
        fi
	if [ ! $KV_PATH ];then
                echo -e "\033[31mThe value of KV_PATH must be set\033[0m" && exit 1
        fi
}

function get_kv(){
	sed -i "s#ROLE_ID#$ROLE_ID#;s#SECRET_ID#$SECRET_ID#" /payload.json
	APP_TOKEN=`curl -s --request POST --data @payload.json $VAULT_ADDR/v1/auth/approle/login|jq -r '.auth.client_token'`
	curl -s --header "X-Vault-Token: $APP_TOKEN"     $VAULT_ADDR/v1/$KV_PATH | jq -r ".data.data" > /vault.txt
}

function creat_env(){
	cat /vault.txt|jq -r keys > /keys.txt && sed -i '1d;$d;s#,$##;s#"##;s#\"$##' /keys.txt
	cat /vault.txt|jq -r .[] > /values.txt 
	paste /keys.txt /values.txt > /kvs.txt
	while read key value;do
		echo "export $key=\"$value\"" >> /etc/profile.d/vault_env.sh
	done < /kvs.txt
	chmod +x /etc/profile.d/vault_env.sh
}

env_test

get_kv

creat_env
